package com.example.cadmin.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cadmin.entity.Host;
import com.example.cadmin.service.HostService;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author zzsoft
 * @since 2023-02-23
 */
@Controller
@RequestMapping("/menu")
public class MenuController {
    @Resource
    private HostService hostService;
    @Resource
    private sendCmd sendCmd;

    /**
     * 发布公告
     */
    @GetMapping("notice")
    public ModelAndView sengNotice() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("notice");
        List<Map<String, Object>> hostList = hostService.listMaps();
        modelAndView.addObject("hostList", hostList);
        return modelAndView;
    }

    /**
     * 发布公告-单机发送
     */
    @PostMapping("/notice/send")
    @ResponseBody
    public ResponseModel noticeSend(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("number")) || StrUtil.isEmpty(data.getStr("content"))) {
            return ResponseModel.success("缺少参数");
        }
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", data.getStr("number")));
        sendCmd.send("NOTICETCP:" + data.getStr("content"), null, host.getIp());
        return ResponseModel.success("公告已发送" + data.getStr("number"));
    }

    /**
     * 发布公告-发送全部
     */
    @PostMapping("/notice/send/all")
    @ResponseBody
    public ResponseModel noticeSendAll(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("content"))) {
            return ResponseModel.success("缺少参数");
        }
        List<Host> hostList = hostService.list();
        for (Host host : hostList) {
            sendCmd.send("NOTICETCP:" + data.getStr("content"), null, host.getIp());
        }
        return ResponseModel.success("公告已发送" + data.getStr("number"));
    }
}
